<template>
  <div>
    <!--   若书本不为空-->
    <template v-if="book">
      <book-details
          :title="book.title"
          :id="book.id"
          :price="book.price"
          :author="book.author"
          :category="category"
          :publisher="book.publisher"
          :img="book.imgUrl"
          :average="averageScore"
          @add-cart="addToCart"/>
      <comment-pane :comments="comments" @submit="postComment"/>
    </template>

    <el-backtop :visibility-height="200"></el-backtop>
  </div>
</template>

<script>
import axios from "axios";
import BookDetails from "@/components/books/BookDetails";
import {mapState} from "vuex";
import CommentPane from "@/components/comments/CommentPane";

export default {
  name: "BookDetailView",
  components: {CommentPane, BookDetails},
  data() {
    return {
      book: null,
      category: null,
      comments: []
    }
  },
  methods: {
    addToCart(e) {
      if (!this.username) {
        this.$message({
          message: "您还没有登录！",
          type: "error"
        });
        return;
      }
      let {id, count} = e
      let loading = this.$loading({
        fullscreen: true,
        lock: true
      });
      axios.post(`/api/cart/add`, {
        id,
        cnt: count
      })
          .then(() => {
            loading.close();
            this.$message({
              message: "操作成功",
              type: "success"
            });
          })
          .catch(e => {
            loading.close();
            if (e.response) {
              this.$message({
                message: `未知的服务器错误 代码${e.response.status}`,
                type: "error"
              });
            } else {
              this.$message({
                message: `未知的错误`,
                type: "error"
              });
            }
          })
    },
    postComment(e) {
      let loading = this.$loading({
        fullscreen: true,
        lock: true
      });
      let data = {...e, bookId: this.id}
      axios.post('/api/comment/add', data)
          .then(() => {
            this.comments.unshift({
              username: this.username,
              content: data.content,
              score: data.score
            });
            loading.close();
            this.$message({
              message: '发表成功！',
              type: "success"
            });
          })
          .catch(e => {
            if (e.response) {
              this.$message({
                message: `未知的服务器错误 代码${e.response.status}`,
                type: "error"
              });
            } else {
              this.$message({
                message: `未知的错误`,
                type: "error"
              });
            }
          })
    },
    fetchBookDetails() {
      // 获取商品详情
      axios.get(`/api/book/fetch?id=${this.id}`)
          .then(res => {
            this.book = res.data;
            return axios.get(`/api/book/fetchCategory?id=${this.book.categoryId}`);
          })
          .then(res => {
            this.category = res.data;
          })
          .catch(e => {
            if (e.response) {
              if (e.response.status === 404) {
                this.$message({
                  message: `不存在的图书ID`,
                  type: "error"
                });
              } else {
                this.$message({
                  message: `未知的服务器错误 代码${e.response.status}`,
                  type: "error"
                });
              }
            } else {
              this.$message({
                message: `未知的错误`,
                type: "error"
              });
            }
          })
    },
    fetchComments() {
      // 获取评论
      axios.get(`/api/comment/show?bookId=${this.id}`)
          .then(res => {
            this.comments = res.data;
          })
          .catch(e => {
            if (e.response) {
              this.$message({
                message: `未知的服务器错误 代码${e.response.status}`,
                type: "error"
              });
            } else {
              this.$message({
                message: `未知的错误`,
                type: "error"
              });
            }
          })
    }
  },
  props: {
    id: {
      required: true,
      type: String
    }
  },
  computed: {
    averageScore() {
      let sum = 0
      for (let i of this.comments) {
        sum += i.score
      }
      return sum / this.comments.length
    },
    ...mapState(['username'])
  },
  beforeMount() {
    this.fetchBookDetails();
    this.fetchComments();
  },
  beforeRouteUpdate(to, from, next) {
    next(false)  // 禁止详情页内跳转
  }
}
</script>

<style scoped>

</style>